<template>
  <div class="job-page">
    <!-- 搜索栏区域，简单模拟，可扩展真实搜索逻辑 -->
    <div id="searchInput">
      <search></search>
    </div>

    <!--筛选-->
    <div class="filter-bar">
      <el-dropdown v-for="(item, index) in filterItems" :key="index" trigger="click" class="filter-item">
        <span class="el-dropdown-link">
          {{ item.label }}
          <template v-if="selectedCount[item.label] > 0">
            ({{ selectedCount[item.label] }})
          </template>▼
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-checkbox-group v-model="selectedOptions[item.label]" @change="handleCheckChange(item.label)">
            <el-checkbox v-for="(option, optIndex) in item.options" :key="optIndex" :label="option"
              class="block-checkbox">
              {{ option }}
            </el-checkbox>
          </el-checkbox-group>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button type="text" class="clear-all-btn" @click="clearAll">
        清除全部
      </el-button>
    </div>

    <div id="job-content" style="display: flex; padding: 20px;">
      <!-- 左侧职位列表 -->
      <div class="recruitment-system">
        <!-- 公司列表 -->
        <div class="company-section">
          <el-card v-for="company in companyList" :key="company.id" class="job-card"
            @click.native="selectCompany(company.companyId)">
            <div class="company-header">
              <div class="company-info">
                <el-avatar :src="company.avatar" size="big" class="company-logo"></el-avatar>

                <div class="text-info">
                  <div class="company-name">{{ company.name }}</div>
                  <div class="job-tags" style="margin-top: 8px;">
                    <span><i class="el-icon-time"></i> {{ company.location }}</span>

                  </div>
                </div>
              </div>
              <div class="company-stats">
                <span>{{ company.recruiterNum }} 位BOSS</span>
                <span>{{ company.positionNum }} 位岗位</span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 岗位列表 -->
        <div class="job-section">
          <el-card v-for="job in jobList" :key="job.positionId" class="job-card" @click.native="selectJob(job)"
            :class="{ 'active-job': selectedJob && selectedJob.positionId === job.positionId }">
            <div class="job-content">
              <div class="job-title-salary">
                <span class="job-title">{{ job.positionName }}</span>
                <span class="job-salary">{{ job.lowestSalaryMonth }} - {{ job.highestSalaryMonth }} </span>
              </div>
              <div class="job-tags" style="text-align: left;">
                <span><i class="el-icon-time"></i> {{ job.positionType }}</span>
              </div>
              <div class="job-meta">
                <span> <i class="el-icon-office-building"></i>{{ job.companyName }}</span>
                <span class="job-location">{{ job.location }}</span>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <!-- 右侧职位详情 -->
      <div class="job-detail">
        <JobDetail :positionId="selectedJob.positionId" />
      </div>
    </div>
  </div>
</template>

<script>
import { searchInput } from '@/util/seeker_api/search_api'
import search from '@/components/SearchInput.vue'
import { mapState } from 'vuex';
import JobDetail from '@/views/SeekerViews/JobPage/JobDetail/JobDetail.vue'
import { getJobIndustry } from '@/util/seeker_api/job_api.js'

export default {
  components: {
    search,
    JobDetail
  },
  data() {
    return {
      filterItems: [
        { label: '薪资待遇', options: ['3K以下', '3-5K', '5-10K', '10-20K', '20-50K', '50K以上'] },
        { label: '学历要求', options: ['博士', '硕士', '本科', '专科', '其他'] },

        { label: '职位类别', options: [] },
      ],
      educationMap: {
        OTHER: '其他',
        MASTER: '硕士',
        UNDERGRADUATE: '本科',
        COLLEGE: '专科',
        DOCTOR: '博士'
      },
      // 存储每个筛选项的选中值，对象的键是筛选项label，值是选中的选项数组
      selectedOptions: {},
      // 存储每个筛选项的选中数量，对象的键是筛选项label，值是数量
      selectedCount: {},
      jobList: null,
      companyList: null,
      selectedJob: null // 用于存储当前选中查看详情的职位
    }
  },
  methods: {
    //获取数据
    async getJobList(searchForm) {
      const res = await searchInput(searchForm);
      //处理数据（后面处理筛选）
      console.log("搜索结果：", res.data);
      this.originalJobList = res.data.jobRespList || [];
      this.originalCompanyList = res.data.companyRespList || [];
      if (this.$route.query.job) {
        this.originalJobList.unshift(this.$route.query.job);
      }
      //数组去重
      function uniqueJobs(jobs) {
        const seen = new Set(); // 用于记录已出现的唯一标识
        return jobs.filter(job => {
          // 以 positionId 作为唯一标识（根据实际字段调整）
          const id = job.positionId;
          // 如果未出现过，则保留并记录；否则过滤掉
          if (!seen.has(id)) {
            seen.add(id);
            return true;
          }
          return false;
        });
      }
      this.originalJobList = uniqueJobs(this.originalJobList);

      this.jobList = [...this.originalJobList];
      this.companyList = [...this.originalCompanyList]; // 公司列表不筛选，始终显示全部
      this.selectedJob = this.jobList[0] || null;
    },

    // 处理复选框选中变化
    handleCheckChange(label) {
      const count = this.selectedOptions[label].length;
      this.$set(this.selectedCount, label, count);
      this.filterData();
    },

    /** 筛选岗位数据 */
    filterData() {
      let filteredJobs = [...this.originalJobList];

      // 1. 薪资待遇筛选（满足任意一个选中的薪资区间）
      const salaryOptions = this.selectedOptions['薪资待遇'] || [];
      if (salaryOptions.length > 0) {
        // 定义各薪资选项对应的区间范围
        const optionRanges = {
          '3K以下': { min: 0, max: 3000 },
          '3-5K': { min: 3000, max: 5000 },
          '5-10K': { min: 5000, max: 10000 },
          '10-20K': { min: 10000, max: 20000 },
          '20-50K': { min: 20000, max: 50000 },
          '50K以上': { min: 50000, max: Infinity } // 50K以上用Infinity表示上限
        };

        filteredJobs = filteredJobs.filter(job => {
          const jobMin = job.lowestSalaryMonth || 0;
          const jobMax = job.highestSalaryMonth || 0;

          // 检查是否与任一选中的薪资选项有交集
          return salaryOptions.some(option => {
            const { min: optMin, max: optMax } = optionRanges[option] || {};
            if (!optMin && optMin !== 0) return false; // 处理未知选项

            // 核心交集判断：两个区间有重叠
            return jobMin < optMax && jobMax > optMin;
          });
        });
      }

      // 2. 学历要求筛选（满足任意一个选中的学历）
      const educationOptions = this.selectedOptions['学历要求'] || [];
      if (educationOptions.length > 0) {
        filteredJobs = filteredJobs.filter(job => {
          const educationText = this.educationMap[job.education] || '其他';
          // 满足任意一个选中的学历
          return educationOptions.some(option =>
            option === educationText
          );
        });
      }

      // 3. 职位类别筛选（满足任意一个选中的类别）
      const positionOptions = this.selectedOptions['职位类别'] || [];
      if (positionOptions.length > 0) {
        filteredJobs = filteredJobs.filter(job => {
          // 满足任意一个选中的类别
          return positionOptions.some(option =>
            option === job.positionType
          );
        });
      }

      // 更新岗位列表和选中职位
      this.jobList = filteredJobs;
      this.selectedJob = this.jobList[0] || null;

      // （可选）联动筛选公司列表
      this.filterCompaniesByJobs(filteredJobs);
    },

    // 清除全部选中项
    clearAll() {
      this.filterItems.forEach(item => {
        this.selectedOptions[item.label] = [];
        this.selectedCount[item.label] = 0;
      });
      this.filterData();
      console.log('已清除全部筛选条件');
    },

    selectJob(job) {
      this.selectedJob = job;
      console.log(this.selectedJob);
    },

    // 获取所有职位行业
    async getCompanyIndustry() {
      try {
        const response = await getJobIndustry();

        console.log("获取所有公司行业成功", response.data);

        const newIndustries = response.data.map(item => item.industryName);
        this.filterItems[2].options.push(...newIndustries);
      } catch (error) {
        console.error('获取公司行业失败', error);
      }
    },

    selectCompany(id) {
      this.$router.push({
        name: 'seekerCompanyDetail',
        query: { id: id }
      })
    },

  },
  created() {
    if (this.$route.query.searchForm) {
      this.getJobList(this.$route.query.searchForm);
    } else {
      this.getJobList({
        content: '',
        location: ''
      });
    }
    // 初始化selectedOptions和selectedCount，给每个筛选项对应空数组和数量0
    this.filterItems.forEach(item => {
      this.$set(this.selectedOptions, item.label, []);
      this.$set(this.selectedCount, item.label, 0);
    });
    this.getCompanyIndustry();

  },
  computed: {
    ...mapState('seeker', {
      userInfo: state => state.userInfo
    })
  },
  watch: {
    // 监听路由中searchForm参数的变化
    '$route.query.searchForm'(newSearchForm, oldSearchForm) {
      if (newSearchForm !== oldSearchForm) {
        console.log('路由searchForm参数变化：', newSearchForm);
        const parsedForm = newSearchForm;
        this.getJobList(parsedForm);
      }
    }
  },

}
</script>

<style scoped>
.filter-bar {
  display: flex;
  gap: 20px;
  margin-left: 10%;
  margin-top: 20px;
}

.el-dropdown-link {
  background: #fff;
  padding: 5px;
  border-radius: 5px;
}

.clear-all-btn {
  margin-left: auto;
  color: #685e5e;
}

.clear-all-btn:focus {
  color: #026e62;
}

.clear-all-btn:hover {
  color: #026e62;
}

.block-checkbox {
  display: block;
  margin-bottom: 8px;
  margin-left: 6px;
}

#job-content {
  margin-top: auto;
  margin-left: 5%;
  display: flex;
  height: 75vh;
  overflow: hidden;
}

.recruitment-system {
  width: 30%;
  height: 100%;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #ddd #f5f5f5;
}

/*公司列表样式 */
.company-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.company-stats {
  display: flex;
  flex-direction: column;
  /* 纵向排列 */
  gap: 8px;
  /* 纵向间距（可调整） */
  align-items: flex-start;
  /* 关键：左对齐（默认值，但显式设置更清晰） */
  /* 可选：如果需要与左侧内容保持视觉平衡，可添加左内边距 */
  /* padding-left: 16px; */
}

.company-stats span {
  font-size: 18px;
}

/*职位列表的样式*/
.job-card {
  padding: auto;
  width: 95%;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: none;
}

.job-card:hover {
  box-shadow: 0px 2px 5px 3px rgba(0, 0, 0, 0.1);

}

.active-job {
  border: 2px solid #026e62 !important;

}

.job-content {}


.job-title-salary {
  align-items: baseline;
  margin-bottom: 15px;
  display: flex;
  /* 开启 Flex 布局 */
  justify-content: space-between;
}

.job-title {
  font-size: 16px;
  margin-top: auto;
}

.job-salary {
  font-size: 18px;
  color: red;
}

.job-tags {
  margin-bottom: 15px;
}

.job-tags>span {
  width: 100%;
  margin-left: auto;
  font-size: 14px;
  background: #f3f5f7;
  padding: 5px;
  border-radius: 5px;
}

.job-meta {
  display: flex;
  /* 开启 Flex 布局 */
  justify-content: space-between;
}

.job-location {
  font-size: 14px;
  padding-left: 20%;
}

.job-detail {
  width: 60%;
  height: 100%;
  margin-left: 20px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0px 2px 5px 3px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  /* 可选：美化滚动条 */
  scrollbar-width: thin;
  scrollbar-color: #ddd #f5f5f5;
}
</style>